import { isMatrix, _o } from '../math/index.js';
import { _colors } from '../color/index.js'
import {
    _props, _centre, _texts, _vertex, _radius,
    _incircle, _excircle, _edge, _links, _edgeExtension
} from "./canvas.js";

import { _show, _borderPoints, _mergeProps, _colorProps, _merge, _mirrorColor } from '../common/index.js'
import { _mirror } from './mirror.js';
import { _mark } from './mark.js';
import { _fill } from './fill.js';


export const _path = (ctx, options, props) => {
    ctx.save()
    ctx.beginPath()
    _props(ctx, props)
    let {
        o = [400, 300], r = 100,
        points, mirror,
        centre,
        vertex,
        labels,
        radius,
        excircle,
        incircle,
        links,
        edge,
        edgeExtension,
        mark,
        fill
    } = options


    if (isMatrix(points)) {
        let mirrorPoints = _borderPoints(points)
        let n = points.length
        let color = mirror && mirror.color ? _mirrorColor(mirror) : options.color
        let _newProps = _colorProps(color, n)
        points.forEach((t, i) => {
            let newProps = _merge(props, _newProps(i))
            _path(ctx, {
                ...options,
                points: t,
                mirrorPoints,
                edge: {
                    ...edge,
                    ...newProps
                }
            }, newProps)
        })
    } else {
        if (edge) {
            if (_show(edge)) {
                _edge(ctx, options, { ...props, ...edge })
            }
        } else {
            _edge(ctx, options, props)
        }


        // 边延长线
        if (_show(edgeExtension)) {
            _edgeExtension(ctx, {
                points,
                edgeExtension
            }, { ...props, ...edgeExtension })
        }

        // 顶点
        if (_show(vertex)) {
            _vertex(ctx, points, { ...props, ...vertex })
        }

        // 中心点
        if (_show(centre)) {
            let o = _o(points)
            _centre(ctx, o, { ...props, ...centre })
        }
        // 半径
        if (_show(radius)) {
            _radius(ctx, { points }, { ...props, ...radius })
        }
        // 外切圆
        if (_show(excircle)) {
            _excircle(ctx, { o, r }, { ...props, ...excircle })
        }
        // 内切圆
        if (_show(incircle)) {
            _incircle(ctx, { o, points }, { ...props, ...incircle })
        }

        // 链接线
        if (_show(links)) {
            _links(ctx, points, { ...props, ...links })
        }

        // 文字
        if (_show(labels)) {
            _texts(ctx, points, { ...props, ...labels })
        }

        // 标注
        if (_show(mark)) {
            _mark(ctx, { points, mark }, { ...props, ...mark })
        }


        // 镜像，被mirrorPoints代替
        if (_show(mirror)) {
            _mirror(ctx, options, props)
        }

        if (_show(fill)) {
            _fill(ctx, { points, fill }, { ...props, ...fill })
        }

    }
    ctx.restore()
}